package com.scalar.chiptrack.operations.dataentry.lotcorrection.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.dataentry.dao.DataEntryDAO;
import com.scalar.chiptrack.operations.dataentry.lotcorrection.LotCorrection;
import com.scalar.chiptrack.operations.dataentry.lotcorrection.LotCorrectionHelper;
import com.scalar.chiptrack.operations.dataentry.lotcorrection.forms.LotChangeForm;

import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.LotDAO;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.Lot;

import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * User: Ganesh
 * Date: Dec 14, 2006
 * Time: 5:44:54 PM
 */
public class LotChangeAction extends ChipTrackAction
{
	private static final String ACTION_NAME = "/lotCorrection.do";

	public ActionForward execute (ActionMapping mapping,
								 ActionForm form,
								 HttpServletRequest request,
								 HttpServletResponse response)
								 throws Exception
	{
		ActionForward actionForward = mapping.findForward( "lotChange" );
		HttpSession session = request.getSession();
        LotDetails lotDetails = new LotDetails();
        boolean success = false;

        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
		if ( user == null )
		{
			session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME );
			return ( mapping.findForward ( "login" ) );
		}
        else
        {
            if ( user.isActionAllowed ( Functionality.LOT_CORRECTION, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

		HashMap errors		        = new HashMap();
		HashMap info    	        = new HashMap();
		String action		        = request.getParameter( "action" );
		String type			        = request.getParameter( "type" );
		String confrim		        = "false";
		LotChangeForm lotChangeForm = ( LotChangeForm )form;
        LotCorrectionHelper lotCorrectionHelper = LotCorrectionHelper.getInstance();
        VendorLocation location ;
        if( type == null )
		{
			type = (String) request.getAttribute( "type" );
		}

		if( session.getAttribute( "ConfrimLotChange" ) != null )
		{
			confrim = (String) session.getAttribute( "ConfrimLotChange" );
		}

		if( action == null || "null".equalsIgnoreCase( action ) )
		{
			ArrayList processTypeList = lotCorrectionHelper.getProcessList();

            session.setAttribute    ( "processList", processTypeList );
			session.removeAttribute ( "productList" );
			session.removeAttribute ( "locationsList" );
			session.removeAttribute ( "lotNumbersList" );
			session.removeAttribute ( "LotInfo" );
			session.removeAttribute ( "newLocationList" );
			session.removeAttribute ( "newProductList" );

            lotChangeForm.setProcessStepId( "0" );
			lotChangeForm.setProcessType( "0" );
			lotChangeForm.setPrevDateIn( "0" );
			lotChangeForm.setPrevQtyIn( "0" );
			lotChangeForm.setPrevLotExists( false );

		}
		else if( "loadProducts".equals( action ) )
		{
			try
			{
				session.setAttribute ( "productList", NewProductDAO.loadPartNumbers(null, 0, lotChangeForm.getProcessType(), true , true, true, 0) );
				session.removeAttribute( "locationsList" );
				session.removeAttribute( "lotNumbersList" );
				session.removeAttribute( "LotInfo" );

                if( "-1".equals ( lotChangeForm.getProcessStepId() )  )
                {
                    errors.put ( "Please Select Valid Product Name", null );
                }
                else
                {
                    lotChangeForm.setProcessStepId( "0" );
                }
				session.removeAttribute( "newLocationList" );
				session.removeAttribute( "newProductList" );

                lotChangeForm.setPrevDateIn( "0" );
				lotChangeForm.setPrevQtyIn( "0" );
				lotChangeForm.setPrevLotExists( false );
			}
			catch( Exception e )
			{
				errors.put( "Error while retreiving the product list", null );
			}
		}
		else if( "loadLocations".equals( action ) )
		{
			try
			{
                ArrayList locationList;
                ArrayList lotChangeLocationsLableValueBeans= new ArrayList();
                lotChangeLocationsLableValueBeans= lotCorrectionHelper.getLocationList(lotChangeForm.getProcessStepId());
                /*locationList = DataEntryDAO.getSelectedLocations( Integer.parseInt(lotChangeForm.getProcessStepId() ) );
                for ( int i = 0; i < locationList.size(); i++ )
                {
                    location = (VendorLocation) locationList.get(i);
                    lotChangeLocationsLableValueBeans.add(new org.apache.struts.util.LabelValueBean(location.getLocationName(), location.getLocationID()));
                }
                */
                session.setAttribute( "locationsList", lotChangeLocationsLableValueBeans );
				session.removeAttribute( "lotNumbersList" );
				session.removeAttribute( "LotInfo" );
				lotChangeForm.setLocationId( "0" );
				session.removeAttribute( "newLocationList" );
				session.removeAttribute( "newProductList" );
				lotChangeForm.setPrevDateIn( "0" );
				lotChangeForm.setPrevQtyIn( "0" );
				lotChangeForm.setPrevLotExists( false );
			}
			catch( Exception e )
			{
				errors.put( "Error while retreiving the location list", null );
			}
		}
		else if( "loadLotNumbers".equals( action ) )
		{
			try
			{
				session.setAttribute( "lotNumbersList", lotCorrectionHelper.getLotNumbersList( lotChangeForm.getProcessStepId(), lotChangeForm.getLocationId() ) );
				lotChangeForm.setLotId( "0" );
				session.removeAttribute( "LotInfo" );
				session.removeAttribute( "newLocationList" );
				session.removeAttribute( "newProductList" );
				lotChangeForm.setPrevDateIn( "0" );
				lotChangeForm.setPrevQtyIn( "0" );
				lotChangeForm.setPrevLotExists( false );
				lotChangeForm.setNewLocationId( "" );
				lotChangeForm.setNewProcessStepId( "" );
			}
			catch( Exception e )
			{
				errors.put( "Error while retreiving the lot numbers list", null );
			}
		}
		else if( "loadLot".equals( action ) )
		{
			try
			{
                LotCorrection lotInfo = DataEntryDAO.getLotInfoByLotIdprocessType( lotChangeForm.getLotId(), lotChangeForm.getProcessType() );
				if( lotInfo != null )
				{
					request.setAttribute( "LotInfo", lotInfo );
					if( type != null && type.equalsIgnoreCase( "product" ) )
					{
                        ArrayList newProductList = null;

                        newProductList = lotCorrectionHelper.getNewProductList(null, 0, lotChangeForm.getProcessType(), true, true, lotChangeForm.getProcessStepId(), 0 );

                        if ( newProductList != null && newProductList.isEmpty() == false )
						{
							session.setAttribute ( "newProductList", newProductList );
						}
						else
						{
							errors.put ( "There are no other products for this Location", "" );
						}
					}
					else
					{
						ArrayList newLocationList = lotCorrectionHelper.getNewLocationList ( lotChangeForm.getProcessStepId(), lotChangeForm.getLocationId() );

						if( newLocationList != null && newLocationList.isEmpty() == false )
						{
							session.setAttribute( "newLocationList", newLocationList );
						}
						else
						{
							errors.put( "There are no other Locations for this Product", "" );
						}
					}
				}
				else
				{
					System.out.println( "Could not fetch the Lot Information" );
					errors.put( "Could not fetch lot information for the Lot ", "" );
				}
			}
			catch( Exception e )
			{
				e.printStackTrace();
				errors.put( "Error while retreiving the lot", null );
			}
			lotChangeForm.setPrevDateIn( "0" );
			lotChangeForm.setPrevQtyIn( "0" );
			lotChangeForm.setPrevLotExists( false );
		}
        else if( "allLotInfo".equals( action ) )
        {
            LotCorrection lotCorrection = null;
            ArrayList allLotsList   = null;
            ArrayList lotsList      = null;
            String newlotId         = null;
            String lotNo            = null;

            if( type != null && type.equalsIgnoreCase( "product" ) )
            {
                String lotId = lotChangeForm.getLotId();
                lotsList = LotDAO.getAllLotDetails( lotId );

                try
                {
                    for ( int i=0; i<lotsList.size(); i++ )
                    {
                        lotCorrection =(LotCorrection)lotsList.get(i);
                    }

                    lotNo = lotCorrection.getLotNumber();

                    newlotId = LotDAO.getLotId( lotNo , lotChangeForm.getLocationId(), lotChangeForm.getNewProcessStepId()   );

                    allLotsList = LotDAO.getAllLotDetails( newlotId );
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                    errors.put( "Error while retreiving the Lot history list", null );
                }
            }
            else if ( type != null && type.equalsIgnoreCase( "location" ) )
            {
                String lotId = lotChangeForm.getLotId();

                lotsList = LotDAO.getAllLotDetails( lotId );

                try
                {
                    for ( int i=0; i<lotsList.size(); i++ )
                    {
                        lotCorrection =(LotCorrection)lotsList.get(i);
                    }
                    lotNo = lotCorrection.getLotNumber();

                    newlotId = LotDAO.getLotId( lotNo, lotChangeForm.getNewLocationId(), lotChangeForm.getProcessStepId() );

                    allLotsList = LotDAO.getAllLotDetails( newlotId );


                }
                catch( Exception e )
                {
                    e.printStackTrace();
                    errors.put( "Error while retreiving the Lot history list", null );
                }
            }

            request.setAttribute( "allLotsList", allLotsList );
            return mapping.findForward( "alllotInfo" );
        }

		else if( "saveLot".equals( action ) )
		{
			DBTransaction dbTransaction = null;                     
            try
			{
				if( confrim == null || confrim.equalsIgnoreCase( "false" ) )
				{
					/*if( type != null && type.equalsIgnoreCase( "product" ) )
					{
						LotCorrection lotCorrection = DataEntryDAO.getLotInfoByLotIdprocessType( lotChangeForm.getLotId(), lotChangeForm.getNewProcessStepId() );
						if( lotCorrection != null  )
						{
							lotChangeForm.setPrevLotExists( true );
							lotChangeForm.setPrevQtyIn ( lotCorrection.getQuantityIn() );
							lotChangeForm.setPrevDateIn ( lotCorrection.getDateIn() );
							info.put ( "Lot already exists for the Product", "" );
							session.setAttribute ( "ConfrimLotChange", "true" );

							lotCorrection = DataEntryDAO.getLotInfoByLotIdprocessType( lotChangeForm.getLotId(), lotChangeForm.getProcessType() );
							request.setAttribute ( "type", type );
							request.setAttribute ( "LotInfo", lotCorrection );
							if( !errors.isEmpty () )
							{
								request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
							}
							request.setAttribute( SessionKeys.INFO_MESSAGES, info );
							return actionForward;
						}
					}
					else if( type != null && type.equalsIgnoreCase( "location" ) )
					{
                        System.out.println("before lotId  = " + lotChangeForm.getLotId() + "location " + lotChangeForm.getNewLocationId());
                        LotCorrection lotCorrection = DataEntryDAO.getLotInfoByLotIdlocationId( lotChangeForm.getLotId(), Integer.parseInt(lotChangeForm.getNewLocationId()));
                        if( lotCorrection != null  )
                        {
                            System.out.println("lotCorrection.getLotId() = " + lotCorrection.getLotId());
                            lotChangeForm.setPrevLotExists( true );
							lotChangeForm.setPrevQtyIn( lotCorrection.getQuantityIn() );
							lotChangeForm.setPrevDateIn( lotCorrection.getDateIn() );
							info.put( "Lot already exists for the Location", "" );
							session.setAttribute( "ConfrimLotChange", "true" );

							//lotCorrection = LotDAO.fetchLotInformation( lotChangeForm.getLotId() );
                            lotCorrection = DataEntryDAO.getLotInfoByLotIdprocessType( lotChangeForm.getLotId(),lotChangeForm.getProcessType() );
                            request.setAttribute( "LotInfo", lotCorrection );
							request.setAttribute( "type", type );
							if( !errors.isEmpty() )
							{
								request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
							}
							request.setAttribute( SessionKeys.INFO_MESSAGES, info );
							return actionForward;
						}
					}*/
				}

                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();
                if( type != null && type.equalsIgnoreCase( "product" ) )
                {
                    DataEntryDAO.changeLotProduct( dbTransaction, lotChangeForm );
                }
                else if ( type != null && type.equalsIgnoreCase( "location" ) )
                {
                    DataEntryDAO.changeLotLocation( dbTransaction, lotChangeForm );
                }
                dbTransaction.commit();
                success = true;
                info.put ( "Lot Correction Information Saved", null );
                actionForward = mapping.findForward( "saveSuccess" );
			}
			catch( Exception e )
			{
				e.printStackTrace();
				errors.put( "Could not save the Lot Information ", "" );
			}
            finally
            {
                if ( dbTransaction != null )
                {
                     if ( !success )
                     {
                         dbTransaction.rollback();
                     }
                 }
            }

        }

		if( !errors.isEmpty() )
		{
			request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
		}

		if( !info.isEmpty() )
		{
			request.setAttribute( SessionKeys.INFO_MESSAGES, info );
		}

		request.setAttribute( "type", type );
		session.setAttribute( "ConfrimLotChange", "false" );

		return actionForward;
	}

    	/**
	 * Returns the list of lots matching the given processStepId and locationId
	 *
	 * @param processStepId
	 * @param locationId
	 * @return
	 */

	private ArrayList getLotList( String processStepId, String locationId ) throws ScalarException
    {
		ArrayList lotList = new ArrayList();
		Lot lot = null;
        ArrayList LotNumberLabelValueBeans= new ArrayList();
        lotList = new ArrayList ();

        lotList = DataEntryDAO.getRunningLotNumbersByPSTypeName( processStepId, locationId );
        for (int i = 0; i < lotList.size(); i++)
        {
            lot = (Lot) lotList.get(i);
            LotNumberLabelValueBeans.add(new org.apache.struts.util.LabelValueBean( lot.getLotNumber(), lot.getLotId()));
        }

        return LotNumberLabelValueBeans;
	}
    public static ArrayList getLocationList( String processStepId, String locationId ) throws ScalarException
   	{
        VendorLocation location ;
        ArrayList locationList;
        ArrayList lotNewLocationsLableValueBeans= new ArrayList();
        locationList = DataEntryDAO.getSelectedLocations( Integer.parseInt( processStepId ) );

        for ( int i = 0; i < locationList.size(); i++ )
        {
            location = (VendorLocation) locationList.get(i);
            if(!(locationId.equalsIgnoreCase(location.getLocationID()) ) )
            {
                lotNewLocationsLableValueBeans.add(new org.apache.struts.util.LabelValueBean(location.getLocationName(), location.getLocationID()));
            }
        }
	   	return lotNewLocationsLableValueBeans;
   	}

    /*public static ArrayList getNewProductList( String processType, String processStepId ) throws ScalarException
   	{
        ArrayList partNumberList;
        PartNumber partNumber;
        ArrayList newPartNumbersLableValueBeans = new ArrayList();
        try
        {
            if( processType == null || "0".equalsIgnoreCase ( processType ) )
            {
               // newPartNumbersLableValueBeans = ProductDao.loadAllBaseProducts( null );
            }
            else if ( "Bump Store".equalsIgnoreCase( processType ))
            {
                partNumberList = ProductDao.getPartNumberBySpecificProcess( "Wafer Store" );
                newPartNumbersLableValueBeans = new ArrayList();
                for( int i = 0; i < partNumberList.size(); i++ )
                {
                    partNumber = ( PartNumber )partNumberList.get(i);
                    if( "Wafer Store".equalsIgnoreCase( partNumber.getProcessTypeName() ) && "Bump Store".equalsIgnoreCase( partNumber.getProcessType() ) && (!(processStepId.equalsIgnoreCase(partNumber.getProcessStepId()))))
                    {
                        newPartNumbersLableValueBeans.add ( new org.apache.struts.util.LabelValueBean( partNumber.getPartNumber(), partNumber.getProcessStepId() ) );
                    }
                }
            }
            else if ( "Back Grind".equalsIgnoreCase( processType ))
            {
                partNumberList = ProductDao.getPartNumberBySpecificProcess( "Assembly" );
                newPartNumbersLableValueBeans = new ArrayList();
                for( int i = 0; i < partNumberList.size(); i++ )
                {
                    partNumber = ( PartNumber ) partNumberList.get(i);
                    if( "Assembly".equalsIgnoreCase ( partNumber.getProcessTypeName() ) && "Back Grind".equalsIgnoreCase( partNumber.getProcessType() ) && (!(processStepId.equalsIgnoreCase(partNumber.getProcessStepId()))) )
                    {
                        newPartNumbersLableValueBeans.add ( new org.apache.struts.util.LabelValueBean( partNumber.getPartNumber(), partNumber.getProcessStepId() ) );
                    }
                }
            }
            else
            {
                partNumberList = ProductDao.getPartNumber ( processType );
                for ( int i = 0; i < partNumberList.size (); i++ )
                {
                    partNumber = ( PartNumber ) partNumberList.get ( i );
                    if(!(processStepId.equalsIgnoreCase(partNumber.getProcessStepId())))
                    {
                        newPartNumbersLableValueBeans.add ( new org.apache.struts.util.LabelValueBean ( partNumber.getPartNumber(), partNumber.getProcessStepId() ) );
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return newPartNumbersLableValueBeans;
    }*/
}

